<template>
  <div class="workDetail">
    <el-tabs
      v-model="activeName"
      class="workDetail-tabs"
      tab-position="bottom"
      type="border-card"
      @tab-change="handleChangeTab"
    >
      <el-tab-pane label="业务表单" name="businness">
        <component
          :is="isComponent"
          v-if="taskRouteData.businessId"
          :id="taskRouteData.businessId"
          ref="chindRef"
          v-bind="$props"
        >
          <el-button
            v-if="copyId"
            icon="chatLineRound"
            plain
            type="primary"
            @click="handleReply('reply', null)"
            >回复
          </el-button>
          <el-button
            v-if="processed"
            icon="el-icon-circle-check"
            plain
            type="primary"
            @click="handleComplete('agree')"
            >{{ returnTaskList.length == 0 ? '提交' : '同意' }}
          </el-button>
          <!-- 是否办结 -->
          <el-button
            v-if="processed && completion"
            icon="el-icon-circle-check"
            plain
            type="primary"
            @click="handleComplete('completion')"
            >{{ completion }}1
          </el-button>
          <!-- 走其他人审批 ：如提交总经理审批 -->
          <el-button
            v-if="processed && otherApprovals"
            icon="el-icon-circle-check"
            plain
            type="primary"
            @click="handleComplete('otherApprovals')"
            >{{ otherApprovals }}
          </el-button>
          <!-- <el-button
                                                    icon="el-icon-chat-line-square"
                                                    type="primary"
                                                    @click="handleDelegate"
                                                    >委派</el-button
                                                  >
                                                  <el-button icon="el-icon-thumb" type="success" @click="handleTransfer"
                                                    >转办</el-button
                                                  > -->
          <el-button
            v-if="processed && returnTaskList.length != 0"
            icon="el-icon-refresh-left"
            plain
            type="primary"
            @click="handleReturn"
            >不同意
          </el-button>
          <el-button
            v-if="isCreater && !isFirst"
            icon="Switch"
            plain
            type="primary"
            @click="handleWithdraw"
            >撤回
          </el-button>
          <el-button
            v-if="processed && returnTaskList.length != 0 && !signDisabled"
            icon="CirclePlus"
            plain
            type="primary"
            @click="handleCountersign"
            >加签
          </el-button>
          <el-button
            v-if="processed && returnTaskList.length != 0"
            icon="Switch"
            plain
            type="primary"
            @click="handleTurnApproval"
            >转审批
          </el-button>
          <!-- <el-button
                                                    icon="el-icon-circle-close"
                                                    type="primary"
                                                    plain
                                                    @click="handleReject"
                                                    v-if="processed"
                                                    >拒绝</el-button
                                                  > -->
          <el-button
            v-if="isCirculation"
            icon="Document"
            plain
            type="primary"
            @click="handleComplete('circulation')"
            >传阅
          </el-button>
        </component>
      </el-tab-pane>
      <el-tab-pane label="查看意见" name="record">
        <el-switch
          v-model="orderReverse"
          active-text="时间倒序"
          class="mt-10px ml-20px"
          inactive-color="#1890ff"
          inactive-text="时间正序"
          inline-prompt
          @change="orderReverseFn"
        />
        <el-card class="box-card" shadow="never">
          <el-col :offset="2" :span="20">
            <!--  流程环节中-->
            <div ref="eleRefs" class="block pb-20px">
              <el-timeline>
                <el-timeline-item
                  v-for="(item, index) in historyProcNodeList"
                  :key="index"
                  :color="setColor(item.endTime)"
                  :icon="setIcon(item.endTime)"
                >
                  <div class="mb-10px relative">
                    <label>{{ item.activityName }}</label>
                    <span
                      v-if="item.activityType === 'userTask'"
                      class="ml-10px"
                      >{{ item.assigneeName }}</span
                    >
                    <span
                      v-if="item.activityType === 'userTask'"
                      class="ml-10px"
                      >{{ item.endTime }}</span
                    >
                    <!-- 审批状态 -->
                    <div
                      v-if="item.commentList && item.commentList.length > 0"
                      class="inline-block ml-10px"
                    >
                      <div
                        v-for="(comment, index) in item.commentList"
                        :key="index"
                      >
                        <!-- v-if="comment.type != 8" -->
                        <el-tag :type="approveTypeTag(comment.type)"
                          >{{ commentType(comment.type) }}
                        </el-tag>
                      </div>
                    </div>
                    <span
                      v-if="item.activityType === 'userTask' && item.copyName"
                      class="ml-110px"
                      >抄送：{{ item.copyName }}</span
                    >
                    <el-button
                      class="ml-30px"
                      icon="chatLineRound"
                      plain
                      size="small"
                      style="position: absolute; top: 0; right: 0"
                      type="primary"
                      @click="handleReply('flowReply', item)"
                      >回复
                    </el-button>
                  </div>
                  <el-card
                    v-if="item.activityType === 'startEvent'"
                    class="box-card"
                    shadow="hover"
                  >
                    {{ item.assigneeName }} 在 {{ item.createTime }} 发起流程
                  </el-card>
                  <el-card
                    v-if="
                      (item.activityType === 'userTask' &&
                        item.commentList &&
                        item.commentList.length > 0) ||
                      (item.activityType === 'userTask' &&
                        item.attachmentList &&
                        item.attachmentList.length > 0)
                    "
                    class="box-card bg-#f7fbfe ss"
                    shadow="hover"
                  >
                    <!-- <el-descriptions
                                                                                                        :column="5"
                                                                                                        :labelStyle="{ 'font-weight': 'bold' }"
                                                                                                      >
                                                                                                        <el-descriptions-item label="实际办理：">{{
                                                                                                          item.assigneeName || '-'
                                                                                                        }}</el-descriptions-item>
                                                                                                        <el-descriptions-item label="候选办理：">{{
                                                                                                          item.candidate || '-'
                                                                                                        }}</el-descriptions-item>
                                                                                                        <el-descriptions-item label="抄送：">{{
                                                                                                          item.copyName || '-'
                                                                                                        }}</el-descriptions-item>
                                                                                                        <el-descriptions-item label="接收时间：">{{
                                                                                                          item.createTime || '-'
                                                                                                        }}</el-descriptions-item>
                                                                                                        <el-descriptions-item label="办结时间：">{{
                                                                                                          item.endTime || '-'
                                                                                                        }}</el-descriptions-item>
                                                                                                        <el-descriptions-item label="耗时：">{{
                                                                                                          item.duration || '-'
                                                                                                        }}</el-descriptions-item>
                                                                                                      </el-descriptions> -->
                    <!-- 状态，建议 -->
                    <div v-if="item.commentList && item.commentList.length > 0">
                      <div
                        v-for="(comment, index) in item.commentList"
                        :key="index"
                      >
                        <span>{{ comment.fullMessage }}</span>
                      </div>
                    </div>

                    <!-- 附件 -->
                    <div
                      v-if="
                        item.attachmentList && item.attachmentList.length > 0
                      "
                      class="mt-10px"
                    >
                      <span class="text-#1890ff">附件：</span>
                      <div
                        v-for="item in item.attachmentList"
                        :key="item.id"
                        class="inline-block"
                      >
                        <a
                          :href="item.url"
                          class="ml-10px text-#1890ff"
                          target="_blank"
                          >{{ item.name }}</a
                        >
                      </div>
                    </div>
                  </el-card>
                  <!-- 抄送人回复的内容 -->
                  <el-card
                    v-if="
                      item.activityType === 'userTask' &&
                      item.copyCommentList &&
                      item.copyCommentList.length > 0
                    "
                    class="box-card bg-#f7fbfe ss"
                    shadow="hover"
                  >
                    <div
                      v-for="(copyItem, index) in item.copyCommentList"
                      :key="index + 'i'"
                    >
                      <p class="m-0">
                        <span class="text-#000">{{ copyItem.userName }}</span>
                        <span class="ml-10px">{{ copyItem.time }}</span>
                      </p>
                      <p class="mt-10px">{{ copyItem.comment }}</p>
                      <!-- 附件 -->
                      <div
                        v-if="
                          copyItem.attachmentList &&
                          copyItem.attachmentList.length > 0
                        "
                        class="my-10px"
                      >
                        <span class="text-#1890ff">附件：</span>
                        <div
                          v-for="item in copyItem.attachmentList"
                          :key="item.id"
                          class="inline-block"
                        >
                          <a
                            :href="item.url"
                            class="ml-10px text-#1890ff"
                            target="_blank"
                            >{{ item.name }}</a
                          >
                        </div>
                      </div>
                    </div>
                  </el-card>
                  <el-card
                    v-if="item.activityType === 'endEvent'"
                    class="box-card"
                    shadow="hover"
                  >
                    {{ item.createTime }} 结束流程
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </div>
            <!-- 传阅-->
            <el-collapse class="mt--20px relative">
              <div style="position: absolute; top: 12px; right: 26px">
                <el-button
                  class="ml-30px"
                  icon="chatLineRound"
                  plain
                  size="small"
                  type="primary"
                  @click="handleReply('flowReply', null)"
                  >回复
                </el-button>
              </div>
              <el-collapse-item
                :title="`查看回复(${replyList.length})`"
                name="reply"
              >
                <div
                  class="block mt-10px mb-20px bg-#f7fbfe p-20px pt-10px ml-40px"
                >
                  <div
                    v-for="(activity, index) in replyList"
                    :key="index"
                    class="pt-10px relative"
                  >
                    <div>
                      <span class="text-#303133 font-bold mr-10px">{{
                        activity.sendName
                      }}</span>
                      <span v-if="activity.recvName"> 回复</span>
                      <span
                        v-if="activity.recvName"
                        class="font-bold text-#303133 ml-10px mr-20px"
                        >{{ activity.recvName }}</span
                      >
                      {{ activity.createTime }}
                    </div>
                    <div>
                      {{ activity.content }}
                    </div>
                    <!--                     附件-->
                    <div
                      v-if="activity.sysAttachFiles"
                      class="pb-10px"
                      style="border-bottom: 1px solid #e5e4ec"
                    >
                      <div
                        v-for="item in activity.sysAttachFiles"
                        :key="item.id"
                        class="inline-block"
                      >
                        <a
                          :href="item.url"
                          class="mr-10px text-#1890ff"
                          target="_blank"
                          >{{ item.origFileName }}</a
                        >
                      </div>
                    </div>
                    <div style="position: absolute; top: 12px; right: 4px">
                      <el-button
                        class="ml-30px"
                        icon="chatLineRound"
                        plain
                        size="small"
                        type="primary"
                        @click="handleReply('flowReply', activity)"
                        >回复
                      </el-button>
                    </div>
                  </div>
                </div>
              </el-collapse-item>
              <el-collapse-item name="1" title="传阅记录">
                <div class="block mt-20px">
                  <el-timeline>
                    <el-timeline-item
                      v-for="(activity, index) in circulationList"
                      :key="index"
                      :timestamp="activity.createTime"
                      :type="'primary'"
                      placement="top"
                    >
                      <div>
                        {{ activity.createBy }}
                        <span class="ml-20px"
                          >传阅：{{ activity.assigneeName }}</span
                        >
                      </div>
                    </el-timeline-item>
                  </el-timeline>
                </div>
              </el-collapse-item>
            </el-collapse>
          </el-col>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="查看流程" name="track">
        <!-- 高亮流程图 -->
        <my-process-viewer
          key="designer"
          v-model="xmlData"
          :activityData="activityList"
          :prefix="bpmnControlForm.prefix"
          :processInstanceData="processInstance"
          :taskData="tasks"
          :value="xmlData"
          v-bind="bpmnControlForm"
        />
      </el-tab-pane>
    </el-tabs>
    <!--加签表单-->

    <!-- 24020702 lg -->
    <el-dialog v-model="signOpen" :title="signTitle" append-to-body width="700">
      <el-form
        ref="signForm"
        :model="taskHand"
        :rules="rules"
        label-width="140px"
      >
        <el-form-item
          label="添加审批人："
          prop="copyUserIdsUUID"
          v-if="signTitle !== '撤回流程'"
        >
          <el-select
            v-model="taskHand.copyUserIdsUUID"
            class="w-full"
            multiple
            placeholder="请选择审批人"
            @focus="userInputFocus('copyUserIds')"
          >
            <el-option
              v-for="(item, index) in selectOptionObj['copyUserIds']"
              :key="index"
              :disabled="item.disabled"
              :label="item.label"
              :value="item.uuid"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          :label="signInfo.label"
          :rules="signInfo.rules || []"
          prop="comment"
        >
          <el-input
            v-model="taskHand.comment"
            :rows="5"
            maxlength="300"
            placeholder="请输入意见"
            show-word-limit
            type="textarea"
          />
        </el-form-item>

        <el-form-item label="说明：">
          <span style="color: red"> {{ signInfo.notes }}</span>
        </el-form-item>
      </el-form>

      <div class="footer dialog-footer text-right">
        <el-button
          @click="
            () => {
              signOpen = false
            }
          "
          >取 消
        </el-button>
        <el-button :loading="btnLoading" type="primary" @click="submitSign"
          >确 定
        </el-button>
      </div>
    </el-dialog>
    <!--流程表单-->
    <el-dialog
      v-model="returnOpen"
      :title="returnTitle"
      append-to-body
      width="700"
    >
      <el-form
        ref="taskForm"
        :model="taskHand"
        :rules="rules"
        label-width="140px"
      >
        <div v-if="returnTitle != '传阅'">
          <el-form-item
            :label="taskHand.type == 'flowReply' ? '内容：' : '签署意见：'"
            prop="comment"
          >
            <el-input
              v-model="taskHand.comment"
              :placeholder="
                taskHand.type == 'flowReply'
                  ? '请输入回复内容'
                  : '请输入签署意见'
              "
              :rows="5"
              maxlength="300"
              show-word-limit
              type="textarea"
            />
          </el-form-item>
          <el-form-item label="意见附件：">
            <el-upload
              v-model:file-list="taskHand.fileList"
              :before-upload="beforeAvatarUpload"
              :http-request="handleFileChange"
              :show-file-list="false"
              accept=".rar, .zip, .doc, .docx, .pdf"
              action="#"
              class="upload-demo"
            >
              <el-button style="font-size: 14px" type="default">
                <el-icon>
                  <UploadFilled />
                </el-icon>
                上传
              </el-button>
              <template #tip>
                <div class="el-upload__tip float-right">
                  支持格式：.rar .zip .doc .docx .pdf ，单个文件不能超过20MB
                </div>
              </template>
            </el-upload>
            <div class="text-14px mt-10px" style="width: 100%">
              <div v-for="(item, index) in fileList" :key="item.fileId">
                <a :href="item.url" class="text-#409eff" target="_blank">{{
                  item.origFileName
                }}</a>
                <el-button plain text @click="delFileName(index)"
                  >删除
                </el-button>
              </div>
            </div>
          </el-form-item>
          <el-form-item
            v-if="
              taskHand.taskName &&
              taskHand.type != 'reject' &&
              taskHand.type != 'return' &&
              taskHand.type != 'reply' &&
              taskHand.type != 'flowReply'
            "
            label="下一环节："
            prop="taskName"
          >
            <el-input v-model="taskHand.taskName" disabled type="input" />
          </el-form-item>
          <el-form-item
            v-if="taskHand.type == 'return'"
            label="退回节点："
            prop="targetKey"
          >
            <el-radio-group
              v-model="taskHand.targetKey"
              @change="returnTaskSelect"
            >
              <el-radio-button
                v-for="item in returnTaskList"
                :key="item.id"
                :label="item.id"
                >{{ item.name }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            v-if="
              (taskHand.taskName || taskHand.type == 'return') &&
              taskHand.type != 'reject' &&
              taskHand.type != 'reply' &&
              taskHand.type != 'flowReply'
            "
            :label="
              taskHand.type == 'return'
                ? '退回节点处理人：'
                : '下一环节处理人：'
            "
            prop="nextUserIdsUUID"
          >
            <el-input
              v-if="appointUserName"
              v-model="taskHand.nextUserIdsUUID"
              disabled
              type="input"
            />
            <el-select
              v-else
              v-model="taskHand.nextUserIdsUUID"
              :disabled="taskHand.isSelset"
              :placeholder="
                JSON.stringify(taskHand.nextUserIdsUUID) != '[]'
                  ? ''
                  : taskHand.type == 'return'
                  ? '请选择退回节点处理人'
                  : '请选择下一环节处理人'
              "
              class="w-full"
              multiple
              @focus="userInputFocus('nextUserIds')"
            >
              <el-option
                v-for="(item, index) in selectOptionObj['nextUserIds']"
                :key="index"
                :disabled="item.disabled"
                :label="item.label"
                :value="item.uuid"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item
          v-if="taskHand.type != 'reply' && taskHand.type != 'flowReply'"
          :label="returnTitle == '传阅' ? '传阅：' : '抄送：'"
          prop="copyUserIdsUUID"
        >
          <el-select
            v-model="taskHand.copyUserIdsUUID"
            :placeholder="returnTitle == '传阅' ? '请选择传阅' : '请选择抄送'"
            class="w-full"
            multiple
            @focus="userInputFocus('copyUserIds')"
          >
            <el-option
              v-for="(item, index) in selectOptionObj['copyUserIds']"
              :key="index"
              :disabled="item.disabled"
              :label="item.label"
              :value="item.uuid"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="taskHand.type == 'flowReply'"
          label=""
          prop="copyUserIdsUUID"
        >
          <el-checkbox v-model="replyRecvObj.informAllFlag"
            >提醒流程参与人
          </el-checkbox>
        </el-form-item>
      </el-form>

      <div class="footer dialog-footer text-right">
        <el-button
          @click="
            () => {
              returnOpen = false
            }
          "
          >取 消
        </el-button>
        <el-button :loading="btnLoading" type="primary" @click="submitReturn"
          >确 定
        </el-button>
      </div>
    </el-dialog>
    <!-- 弹出框选择人员 下拉框 -->
    <SelectDialog
      :dialog-param="dialogParamUse"
      @close="closeFn"
      @ok="selectDialogData"
    ></SelectDialog>
  </div>
</template>

<script name="WorkDetail" setup>
import { ElLoading } from 'element-plus'
import { defineAsyncComponent, nextTick } from 'vue'
import { getDeptStaffTreeData } from '@/api/system/dept'
import {
  getPricipalId,
  getTreeNodeByParam,
  getUniqueUserId
} from '@/utils/commo'
import { useRoute, useRouter } from 'vue-router'
import { nextUserTask, getReturnPerson } from '@/api/workflow/model'
import myProcessViewer from '@/components/bpmnProcessDesigner/package/designer/ProcessViewer.vue'
import { detailProcess } from '@/api/workflow/process'
import { uploadFile, delFile } from '@/api/salesManage/contractManage'
import {
  addComment,
  complete,
  addTask,
  delegate,
  transfer,
  rejectTask,
  returnList,
  returnTask,
  addCirculation,
  cyDetailList,
  addReply,
  changeAssigneeTask,
  withdrawTask
} from '@/api/workflow/task'
import useTagsViewStore from '@/store/modules/tagsView'
import { getProStatusByBusinessIds } from '@/api/projectManage/project'
import useCommonStore from '@/store/modules/common'
import useUserStore from '@/store/modules/user'
import { getNodeData } from '@/api/workflow/process'

const userStore = useUserStore()
const commonStore = useCommonStore()
const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()
const commentType = computed(() => {
  return val => {
    switch (val) {
      case '1':
        return '同意'
      case '2':
        return '不同意'
      case '3':
        return '驳回'
      case '4':
        return '委派'
      case '5':
        return '转办'
      case '6':
        return '终止'
      case '7':
        return '撤回'
      case '8':
        return '加签'
    }
  }
})
const approveTypeTag = computed(() => {
  return val => {
    switch (val) {
      case '1':
        return 'success'
      case '2':
        return 'warning'
      case '3':
        return 'danger'
      case '4':
        return 'primary'
      case '5':
        return 'success'
      case '6':
        return 'danger'
      case '7':
        return 'info'
      case '8':
        return 'warning'
    }
  }
})
const btnLoading = ref(false) //按钮加载状态
const data = reactive({
  height: document.documentElement.clientHeight - 205 + 'px;',
  // 模型xml数据
  loadIndex: 0,
  xmlData: undefined,
  historyProcNodeList: [],
  // 部门名称
  deptName: undefined,
  // 部门树选项
  deptOptions: undefined,
  userLoading: false,
  // 用户表格数据
  userList: null,
  deptProps: {
    children: 'children',
    label: 'label'
  },
  // 查询参数
  queryParams: {
    deptId: undefined
  },
  total: 0,
  // 遮罩层
  loading: true,
  taskForm: {
    comment: '', // 意见内容
    procInsId: '', // 流程实例编号
    taskId: '', // 流程任务编号
    copyUserIds: '', // 抄送Id
    vars: '',
    targetKey: '',
    copyUserIdsUUID: [],
    nextUserIdsUUID: []
  },
  rules: {
    taskName: [{ required: true, message: '', trigger: ['blur', 'change'] }],
    nextUserIdsUUID: [
      {
        required: true,
        message: '该项不能为空',
        trigger: ['blur', 'change']
      }
    ],
    targetKey: [
      {
        required: true,
        message: '退回节点不能为空',
        trigger: ['blur', 'change']
      }
    ],
    copyUserIdsUUID: computed(() =>
      !signOpen.value
        ? []
        : [
            {
              required: true,
              message: '添加审批人不能为空',
              trigger: ['blur', 'change']
            }
          ]
    )
  },
  currentUserId: null,
  variables: [], // 流程变量数据
  processFormList: [], // 流程变量数据
  returnTaskList: [], // 回退列表数据
  processed: false,
  copyId: null, //是否是抄送
  returnTitle: null,
  returnOpen: false,
  rejectOpen: false,
  rejectTitle: null,
  taskRouteData: {} //业务关联
})
const {
  height,
  // 模型xml数据
  loadIndex,
  xmlData,
  historyProcNodeList,
  // 部门名称
  deptName,
  // 部门树选项
  deptOptions,
  userLoading,
  // 用户表格数据
  userList,
  deptProps,
  // 查询参数
  queryParams,
  total,
  loading,
  taskForm,
  rules,
  currentUserId,
  variables, // 流程变量数据
  processFormList, // 流程变量数据
  returnTaskList, // 回退列表数据
  copyId,
  processed,
  returnTitle,
  returnOpen,
  rejectOpen,
  rejectTitle,
  taskRouteData
} = toRefs(data)
const taskHand = ref({}) //表单
const isComponent = ref('') //动态组件名
let deptUserData = [] //获取人员的数据
// 获取tab分标签高亮
const activeName = ref('businness')
const flowUseData = ref([]) //设计模型中设置了岗位 获取岗位的人
const appointUserName = ref(null) //绩效特点指定人
const signDisabled = ref(false) //是否禁止加签
const completion = ref(null) //是否办结-发布 ==按钮名称
const otherApprovals = ref(null) //是否走其他审批-审批按钮名称
const circulationList = ref([]) //传阅
const isCirculation = ref(false) //是否显示传阅
const orderReverse = ref(true) //意见查看记录顺序 true倒叙 false 正序
// 获取路由上的信息
function initData() {
  orderReverse.value =
    localStorage.getItem('orderReverse') == 'true' ? true : false //记录顺序
  taskHand.value.procInsId = route.query && route.query.procInsId
  taskHand.value.taskId = route.query && route.query.taskId
  processed.value = route.query && eval(route.query.processed || false)
  isCirculation.value = route.query && eval(route.query.isCirculation || false)
  copyId.value = (route.query && route.query.copyId) || null
  // 流程任务重获取变量表单
  getProcessDetails(taskHand.value.procInsId, taskHand.value.taskId)
  loadIndex.value = taskHand.value.procInsId
}

/** 切换顺便模块 start*/
const eleRefs = ref(null)
/**切换记录顺序*/
const orderReverseFn = e => {
  localStorage.setItem('orderReverse', e)
  historyProcNodeList.value =
    historyProcNodeList.value && historyProcNodeList.value.length > 0
      ? historyProcNodeList.value.reverse()
      : []
  if (!orderReverse.value && eleRefs.value) {
    nextTick(() => {
      //自动固定底部
      eleRefs.value.scrollIntoView({ behavior: 'smooth', block: 'end' })
    })
  }
}
const handleChangeTab = e => {
  console.log(orderReverse.value, e, eleRefs.value, '111')
  if (e != 'record') {
    return false
  }
  if (orderReverse.value == false && eleRefs.value) {
    nextTick(() => {
      console.log('滚动--')
      //自动固定底部
      eleRefs.value.scrollIntoView({ behavior: 'smooth', block: 'end' })
    })
  }
}

/** 切换顺序模块 end */
function setIcon(val) {
  if (val) {
    return 'el-icon-check'
  } else {
    return 'el-icon-time'
  }
}

function setColor(val) {
  if (val) {
    return '#2bc418'
  } else {
    return '#b3bdbb'
  }
}

// ========== 高亮流程图 start ==========
const bpmnControlForm = ref({
  prefix: 'flowable'
})
const activityList = ref([]) //高亮的流程
const processInstance = ref({}) //可展示流程发起人等信息
const tasks = ref([]) //每个节点鼠标以上去显示的 可展示 UserTask 审核相关的信息
// ========== 高亮流程图 end ==========

/**
 *
 * @param {*} arrMenus  传入的数组或者树数据 例 treeData
 * @param {*} val 对比的值 例 1
 */
function dealTreeOnceChecked(arrMenus, val) {
  if (arrMenus.length > 0) {
    arrMenus.forEach(item => {
      if (item.id == val) {
        item.disabled = true
      } else {
        let arrChildren = item.children
        if (arrChildren != null) {
          dealTreeOnceChecked(arrChildren, val)
        }
      }
    })
  }
}

/**根据当前用户回填下一环节处理人 抄送人
 *
 * @param {*} idArr  是对应id值
 * @param {*} type  type 类型 ban 已有抄送人（针对抄送人）  post 指定人岗位
 * @param {*} data  数据源
 * @param {*} isDisabled 回填值不能删除
 * @returns {*
 * selectData  选中的数据集合
 * uuid 选中的uuid
 * ids val值得字符串根式
 * copyData 处理后的源数据
 * }
 */
function getDefaultUserInfo(idArr, type, data, isDisabled) {
  if (!idArr || JSON.stringify(idArr) == '[]') {
    return false
  }
  let uuid = [], //获取uuid
    textArr = [], //获取选中的文字
    selectData = [] //获取数据源
  if (type == 'ban') {
    let deptUserData2 = JSON.parse(JSON.stringify(deptUserData))
    //获取名称
    idArr.map(item => {
      dealTreeOnceChecked(deptUserData2, item) // 已经有的抄送人 不能删除
      let res = getTreeNodeByParam(deptUserData, item, 'id', [])
      if (res.length > 0) {
        selectData.push({ ...res[0], disabled: true })
        uuid.push(res[0].uuid)
      }
    })
    return {
      copyData: deptUserData2,
      val: uuid,
      ids: idArr,
      selectData: selectData
    }
  } else if (type == 'post') {
    let dataCollation = JSON.parse(JSON.stringify(data))
    //岗位的情况
    idArr.map(item => {
      if (isDisabled) {
        dealTreeOnceChecked(dataCollation, item) // 已经选中的人 不能删除
      }
      let res = getTreeNodeByParam(data, item, 'id', [])
      if (res.length > 0) {
        if (isDisabled) {
          selectData.push({ ...res[0], disabled: true })
        } else {
          selectData.push(res[0])
        }
        uuid.push(res[0].uuid)
      }
    })
    return {
      val: uuid,
      ids: idArr.toString(),
      selectData: selectData,
      DataDisabled: dataCollation
    }
  } else {
    // 获取id
    idArr.map(item => {
      let res = getTreeNodeByParam(deptUserData, item, 'id', [])
      if (res.length > 0) {
        if (isDisabled) {
          selectData.push({ ...res[0], disabled: true })
        } else {
          selectData.push(res[0])
        }
        uuid.push(res[0].uuid)
      }
    })
    return { val: uuid, ids: idArr.toString(), selectData: selectData }
  }
}

// 获取抄送人 下一环节人的初始化数据
const getHandleUsers = async type => {
  if (processed.value) {
    //获取抄送人 下一环节人的初始化数据
    let res = await nextUserTask(taskHand.value.taskId, {
      isCompletion: clickBtnType.value === 'completion' ? 'Y' : 'N',
      isOtherApprovals: clickBtnType.value === 'otherApprovals' ? 'Y' : 'N'
    })
    // 已抄送人
    taskHand.value.existedCopyUsers = res.data.copyData //已经存在的数据 不能在传给后端
    appointUserName.value = null
    if (res.data.copyData && res.data.copyData.length > 0) {
      let { selectData, val, ids, copyData } = getDefaultUserInfo(
        res.data.copyData,
        'ban'
      )
      selectOptionObj.value['copyUserIds'] = selectData
      taskHand.value.copyUserIdsUUID = val
      taskHand.value.copyUserIds = ids
      taskHand.value.copyData = copyData
    }
    if (res.data.taskData && res.data.taskData.length > 0) {
      taskHand.value.taskName = res.data.taskData[0].taskName
      // 1. 下一环节处理人分析
      // 1 会签（流程中有A,B人，A指定下一环节人c,B指定下一环节人D） readyUser 已经存在指定人
      let readyUser = res.data.readyUser
        ? res.data.readyUser.split(',').map(Number)
        : []
      if (res.data.taskData[0].hasUser) {
        // 1.1 设计模型里设置指定人 ---- 下一环节 下一环节处理人 有存在下一环节人时 说明走固定模式不能更改
        let hasUser = res.data.taskData[0].hasUser.split(',').map(Number)
        let { selectData, val, ids } = getDefaultUserInfo(hasUser)
        selectOptionObj.value['nextUserIds'] = selectData
        taskHand.value.nextUserIdsUUID = val
        taskHand.value.nextUserIds = ids
        taskHand.value.isSelset = true
      } else if (res.data.taskData[0].postUser) {
        //1.2 设计模型里设置岗位
        let postRes = await getDeptStaffTreeData({
          userIds: res.data.taskData[0].postUser
        })
        let postIds = res.data.taskData[0].postUser.split(',')
        if (postIds.length == 1) {
          //1.2.1 如果该岗位下只有一个用户的时候 默认选中
          let { selectData, val, ids } = getDefaultUserInfo(
            postIds,
            'post',
            postRes.data
          )
          selectOptionObj.value['nextUserIds'] = selectData
          taskHand.value.nextUserIdsUUID = val
          taskHand.value.nextUserIds = ids
          taskHand.value.isSelset = true
        } else {
          //获取该岗位下的下一环节处理人
          if (readyUser.length > 0) {
            //有指定人的情况下
            let { selectData, val, ids, DataDisabled } = getDefaultUserInfo(
              readyUser,
              'post',
              postRes.data,
              true
            )
            selectOptionObj.value['nextUserIds'] = selectData
            flowUseData.value = DataDisabled
            taskHand.value.nextUserIdsUUID = val
            taskHand.value.nextUserIds = ids
            taskHand.value.isSelset = false
          } else {
            flowUseData.value = postRes.data
            taskHand.value.isSelset = false
            taskHand.value.nextUserIdsUUID = []
            taskHand.value.nextUserIds = null
          }
        }
      } else if (
        res.data.taskData[0].appointUserId &&
        res.data.taskData[0].appointUserName
      ) {
        //1.3 绩效业务情况下，指定下一环节人
        taskHand.value.nextUserIds = res.data.taskData[0].appointUserId
        appointUserName.value = res.data.taskData[0].appointUserName
        taskHand.value.nextUserIdsUUID = res.data.taskData[0].appointUserName
      } else {
        //1.4 没有下一环节处理人
        taskHand.value.nextUserIdsUUID = []
        taskHand.value.nextUserIds = null
        taskHand.value.isSelset = false
      }
    } else {
      taskHand.value.taskName = null
    }
    // 1. 获取退回节点人的数据列表
    if (type == 'return') {
      getReturnHandleUsers()
    }
  }
}
/**
 * 获取退回节点人的数据列表
 * @param {*} type
 */
const getReturnHandleUsers = async () => {
  appointUserName.value = null
  // 1.2 获取退回节点的人员
  let returnRes = await getReturnPerson({
    procInsId: taskHand.value.procInsId,
    targetKey: taskHand.value.targetKey
  })
  if (returnRes.data.appointUserId && returnRes.data.appointUserName) {
    //1.3 绩效业务情况下，指定下一环节人
    taskHand.value.nextUserIds = returnRes.data.appointUserId
    appointUserName.value = returnRes.data.appointUserName
    taskHand.value.nextUserIdsUUID = returnRes.data.appointUserName
    return false
  }
  //1.2 获取人员的数组
  let postRes = await getDeptStaffTreeData({
    userIds: returnRes.data.assignee
  })
  let postIds = returnRes.data.assignee.split(',')
  if (postIds.length == 1) {
    //1.2.1 如果该岗位下只有一个用户的时候 默认选中
    let { selectData, val, ids } = getDefaultUserInfo(
      postIds,
      'post',
      postRes.data
    )
    console.log(selectData, val, ids, 'selectData, val, ids ')
    selectOptionObj.value['nextUserIds'] = selectData
    taskHand.value.nextUserIdsUUID = val
    taskHand.value.nextUserIds = ids
    taskHand.value.isSelset = true
  } else {
    //获取该岗位下的下一环节处理人
    flowUseData.value = postRes.data
    taskHand.value.isSelset = false
    taskHand.value.nextUserIdsUUID = []
    taskHand.value.nextUserIds = null
  }
}
/**
 * 退回节点选择
 */
const returnTaskSelect = async () => {
  await getReturnHandleUsers()
}

/*** 获取详情数据 */
// 20240703 lg
const isCreater = ref(false) //是否创建人
const isFirst = ref(false) //是否第一环节
async function getProcessDetails(procInsId, taskId) {
  const params = { procInsId: procInsId, taskId: taskId }
  // 全部人员接口
  deptUserData = await commonStore.getUseTreeData()
  // 获取流程详情接口
  let res = await detailProcess(params)
  console.log(userStore.userInfo.userName)
  isCreater.value = res.data.createBy == userStore.userInfo.userName
  const data = res.data
  xmlData.value = data.bpmnXml
  processFormList.value = data.processFormList
  historyProcNodeList.value =
    orderReverse.value == false &&
    data.historyProcNodeList &&
    data.historyProcNodeList.length > 0
      ? data.historyProcNodeList.map(v => v).reverse()
      : data.historyProcNodeList
  activityList.value = data.historyProcNodeList
  const urls = data.taskRouteData.routeKey.toString()
  isComponent.value = initComponents(urls)
  taskHand.value.variables = {
    businessId: data.taskRouteData.businessId.toString()
  }
  taskRouteData.value = {
    businessId: data.taskRouteData.businessId.toString()
  }

  //   根据业务id获取taskId
  const getTaskIdList = await getProStatusByBusinessIds(
    taskRouteData.value.businessId
  )
  const taskIdObj = getTaskIdList.data.find(v => v.taskId)
  console.log(taskIdObj, 'getTaskId')
  if (taskIdObj) {
    console.log(taskIdObj.taskId)
    processed.value = true
    taskHand.value.taskId = taskIdObj.taskId
  }
  //获取当前流程节点 是否禁止加签
  let flowRes = await getNodeData(data.taskRouteData.businessId.toString())
  signDisabled.value = flowRes.data?.signDisabled
  console.log(flowRes)
  isFirst.value = flowRes?.data?.isFirst === 'Y'
  //是否办结 或发布==按钮名称
  completion.value = flowRes.data.completion ? flowRes.data.completion : null
  //是否走其他审批-审批按钮名称
  otherApprovals.value = flowRes.data.otherApprovals
    ? flowRes.data.otherApprovals
    : null
  await getCyDetailList(data.taskRouteData.businessId.toString())
  await getReturnList()
}

const replyList = ref([]) //回复列表
// 获取传阅的记录
const getCyDetailList = async id => {
  let cyRes = await cyDetailList({ businessId: id })
  // 传阅
  const newData =
    cyRes.data && cyRes.data.cyList
      ? JSON.parse(JSON.stringify(cyRes.data.cyList))
      : []
  let mergedArr = []
  if (newData.length > 0) {
    mergedArr = newData.reduce((acc, curr) => {
      const existingItem = acc.find(
        item =>
          item.createTime === curr.createTime && item.createBy === curr.createBy
      )
      if (existingItem) {
        existingItem.assigneeName += `,${curr.assigneeName}`
        existingItem.id += `,${curr.id}`
        existingItem.assignee += `,${curr.assignee}`
      } else {
        acc.push(curr)
      }
      return acc
    }, [])
  }
  circulationList.value = mergedArr
  replyList.value = cyRes.data.hfList
}
// ========== 动态注册组件 start ==========
const initComponents = url => {
  const modules = import.meta.glob([
    // '@/views/**/**detail.vue',
    // '@/views/**/**Details.vue',
    // '@/views/**/**Details/index.vue',
    '@/views/**/**edit**/index.vue',
    '@/views/**/**edit**.vue',
    '@/views/**/**Edit.vue',
    '@/views/**/**Edit**.vue',
    '@/views/**/edit**.vue',
    '@/views/**/contactsAddOrUpdate/index.vue',
    '@/views/**/customerAddOrUpdate/index.vue',
    '@/views/**/downloadApprove/index.vue',
    '@/views/**/**Form.vue',
    '@/views/**/biddingResults.vue',
    '@/views/rsgl/workOrder/module/orderFrom.vue',
    '@/views/**/add**/index.vue',
    '@/views/sourceManage/supplierManage/applicationManage/AddApplication/index.vue'
  ])

  console.log(url, 'url')
  const link = modules[`/src/views/${url}.vue`]
  console.log(link, 'link')
  return markRaw(defineAsyncComponent(link))
}
// ========== 动态注册组件 end ==========
// ========== 加签 start ==========
const signTitle = ref('')
const signOpen = ref(false)
// 20240703 lg
const signData = ref([
  {
    value: '加签',
    label: '加签意见：',
    notes: '加签完 还需本人再审批,仅增加当前环节的审批人',
    rules: [
      {
        required: true,
        message: '加签意见不能为空',
        trigger: ['blur', 'change']
      }
    ]
  },
  {
    value: '转审批',
    label: '转审批意见：',
    notes: '转审批完 无需本人再审批,仅修改当前审批环节的审批人',
    rules: []
  },
  {
    value: '撤回流程',
    label: '撤回原因：',
    notes: '撤回后可重新进入发起流程',
    rules: [
      {
        required: true,
        message: '撤回原因不能为空',
        trigger: ['blur', 'change']
      }
    ]
  }
])
const signInfo = computed(() => {
  return signData.value.find(v => signTitle.value === v.value) || {}
})

/** 加签 */
async function handleCountersign() {
  taskHand.value.copyUserIdsUUID = []
  taskHand.value.copyUserIds = undefined
  taskHand.value.comment = undefined
  proxy.resetForm('signForm')
  signTitle.value = '加签'
  signOpen.value = true
}

/** 转审批 **/
function handleTurnApproval() {
  // proxy.$modal.confirm('是否确认转审批?').then(async function () {
  // console.log(param, 'param--')
  taskHand.value.copyUserIdsUUID = []
  taskHand.value.copyUserIds = undefined
  taskHand.value.comment = undefined
  proxy.resetForm('signForm')
  signTitle.value = '转审批'
  signOpen.value = true
  // })
}
// 撤回
function handleWithdraw() {
  taskHand.value.copyUserIdsUUID = []
  taskHand.value.copyUserIds = undefined
  taskHand.value.comment = undefined
  proxy.resetForm('signForm')
  signTitle.value = '撤回流程'
  signOpen.value = true
}
/** 流程弹出框 确认按钮 */
function submitSign() {
  proxy.$refs['signForm'].validate(valid => {
    if (valid) {
      if (signTitle.value === '加签') {
        let param = {
          taskId: taskHand.value.taskId,
          comment: '加签 ' + taskHand.value.comment,
          assignee: taskHand.value.copyUserIds?.toString()
        }
        console.log(param, 'param--')
        addTask(param)
          .then(response => {
            proxy.$modal.msgSuccess('操作成功')
            signOpen.value = false
            btnLoading.value = false
            getProcessDetails(taskHand.value.procInsId, taskHand.value.taskId)
          })
          .catch(error => {
            btnLoading.value = false
          })
      } else if (signTitle.value === '转审批') {
        let param = {
          taskId: taskHand.value.taskId,
          comment: taskHand.value.comment,
          assignee: taskHand.value.copyUserIds?.toString()
        }
        console.log(param, 'param--')
        changeAssigneeTask(param)
          .then(response => {
            proxy.$modal.msgSuccess('操作成功')
            signOpen.value = false
            btnLoading.value = false
            // getProcessDetails(taskHand.value.procInsId, taskHand.value.taskId)
            goBack()
          })
          .finally(error => {
            btnLoading.value = false
          })
      } else if (signTitle.value === '撤回流程') {
        let param = {
          procInsId: route.query.procInsId,
          comment: taskHand.value.comment
        }
        console.log(param, 'param--')
        withdrawTask(param)
          .then(response => {
            proxy.$modal.msgSuccess('操作成功')
            signOpen.value = false
            btnLoading.value = false
            goBack()
          })
          .finally(error => {
            btnLoading.value = false
          })
      }
    }
  })
}

// ========== 加签 end ==========
/** 回复 */
const replyRecvObj = ref({
  recvId: null,
  recvName: null,
  informAllFlag: 0
}) //接收人id
async function handleReply(type, row) {
  returnOpenFn()
  returnTitle.value = '回复'
  taskHand.value.type = type
  taskHand.value.comment = type == 'reply' ? '已阅' : undefined
  if (row) {
    replyRecvObj.value.recvId = row.assigneeId || row.assignee || row.sendId
    replyRecvObj.value.recvName = row.assigneeName || row.sendName
  } else {
    replyRecvObj.value.recvId = null
    replyRecvObj.value.recvName = null
  }
  console.log(row, taskHand.value, 'row---', replyRecvObj.value)
  returnOpen.value = true
}

const chindRef = ref(null)
const clickBtnType = ref() // 点击按钮类型 -- 同意 办结（completion） 提交审批（otherApprovals）
/** 通过/同意任务 */
async function handleComplete(type) {
  if (type == 'circulation') {
    returnTitle.value = '传阅'
    taskHand.value.type = 'circulation'
    selectOptionObj.value['copyUserIds'] = []
    taskHand.value.copyUserIdsUUID = []
    taskHand.value.copyUserIds = ''
    taskHand.value.copyData = []
    returnOpen.value = true
    return false
  }
  clickBtnType.value = type
  let errorMsg = null
  try {
    await proxy.$refs['chindRef'].handleSave()
    errorMsg = null
  } catch (error) {
    const { name, message } = error
    errorMsg = message
    console.log('同意/提交 按钮=错误==》', error)
  }
  console.log(errorMsg, 'errorMsg')
  if (
    errorMsg &&
    errorMsg.indexOf('proxy.$refs.chindRef.handleSave is not a function') == -1
  ) {
    return false
  }
  returnOpenFn()
  // 获取抄送人 下一环节人的初始化数据
  await getHandleUsers()
  returnTitle.value = '同意'
  taskHand.value.type = 'complete'
  if (
    (type == 'agree' && returnTaskList.length != 0) ||
    type == 'otherApprovals'
  ) {
    taskHand.value.comment = '同意'
  } else {
    taskHand.value.comment = undefined
  }
  console.log(taskHand.value, '222222222222')
  returnOpen.value = true
}

/** 拒绝任务 */
async function handleReject() {
  // 获取抄送人 下一环节人的初始化数据
  await getHandleUsers()
  returnTitle.value = '拒绝审批单'
  taskHand.value.type = 'reject'
  returnOpen.value = true
}

/** 返回页面 */
function goBack() {
  router.go(-1)
  useTagsViewStore().delView(router.currentRoute.value)
}

/** 获取退回列表 */
async function getReturnList() {
  if (!processed.value) {
    returnTaskList.value = []
    return false
  }
  let newParams = handleQuery(taskHand.value)
  let res = await returnList(newParams) //获取退回的节点数据
  if (res.data && res.data.length == 0) {
    returnTaskList.value = []
    return false
  }
  returnTaskList.value = res.data
  taskHand.value.values = null
  taskHand.value.targetKey =
    res.data && res.data.length > 0 ? res.data[res.data.length - 1].id : ''
}

/** 可退回、不同意任务列表 */
async function handleReturn() {
  returnTitle.value = '不同意'
  taskHand.value.type = 'return'

  returnOpenFn()
  // 获取抄送人 下一环节人的初始化数据
  await getHandleUsers('return')
  returnOpen.value = true
  taskHand.value.comment = '不同意'
}

/**
 *
 js比较两个数组,取出不同的值
 */
const getDiff = (arr1, arr2) => {
  arr1 = JSON.stringify(arr1) == '[]' || !arr1 ? [] : arr1
  arr2 = JSON.stringify(arr2) == '[]' || !arr2 ? [] : arr2
  return [
    ...arr1.filter(item => !arr2.includes(item)),
    ...arr2.filter(item => !arr1.includes(item))
  ]
}
/**
 * 处理参数
 * @param {*} obj
 */
const handleQuery = obj => {
  let params = JSON.parse(JSON.stringify(obj))
  let copyUserIds = getDiff(obj.copyUserIds, toRaw(obj.existedCopyUsers))
  params.copyUserIds = copyUserIds ? copyUserIds.toString() : ''
  params.attachments = fileList.value
  delete params.fileList
  delete params.existedCopyUsers
  delete params.nextUserIdsUUID
  delete params.copyUserIdsUUID
  delete params.type
  delete params.copyData
  delete params.taskName
  delete params.isSelset
  return params
}

/** 流程弹出框 确认按钮 */
function submitReturn() {
  proxy.$refs['taskForm'].validate(valid => {
    if (valid) {
      let newParams = handleQuery(taskHand.value)
      const fileName = []
      if (fileList.value) {
        fileList.value.map((val, curr) => {
          fileName.push(val.fileName)
        })
      }
      switch (taskHand.value.type) {
        case 'flowReply':
          if (fileName.length > 5) {
            proxy.$modal.msgError('文件个数不能超过5')
            return false
          }
          //流程中回复
          btnLoading.value = true
          const informAllFlag = replyRecvObj.value.informAllFlag == true ? 1 : 0
          console.log(informAllFlag, replyRecvObj.value, 'replyRecvObj.value--')
          let flowParams = {
            businessId: taskHand.value.variables.businessId, //业务id
            recvId: informAllFlag == 1 ? '' : replyRecvObj.value.recvId, //接收人id
            recvName: informAllFlag == 1 ? '' : replyRecvObj.value.recvName, //接收人名称
            fileNames: fileName, //文件
            content: taskHand.value.comment,
            procInsId: taskHand.value.procInsId,
            informAllFlag: informAllFlag //通知全体人员标志
          }
          addReply(flowParams)
            .then(response => {
              proxy.$modal.msgSuccess('操作成功')
              returnOpen.value = false
              getProcessDetails(taskHand.value.procInsId, taskHand.value.taskId)
              btnLoading.value = false
            })
            .catch(error => {
              btnLoading.value = false
            })
          break
        case 'reply':
          // 审批中回复
          btnLoading.value = true
          let params = {
            copyId: copyId.value,
            attachments: fileList.value,
            comment: taskHand.value.comment,
            procInsId: taskHand.value.procInsId,
            taskId: taskHand.value.taskId
          }
          console.log(newParams, 'newParams--')
          addComment(params)
            .then(response => {
              proxy.$modal.msgSuccess('操作成功')
              goBack()
              returnOpen.value = false
              btnLoading.value = false
            })
            .catch(error => {
              btnLoading.value = false
            })
          break
        case 'complete':
          btnLoading.value = true
          newParams.variables.isCompletion =
            clickBtnType.value === 'completion' ? 'Y' : 'N'
          newParams.variables.isOtherApprovals =
            clickBtnType.value === 'otherApprovals' ? 'Y' : 'N'
          complete(newParams, 1)
            .then(async response => {
              let errorMsg = null
              try {
                //调用子组件的方法 为了流程成功后保存一些数据
                await proxy.$refs['chindRef'].callbackSave()
                errorMsg = null
              } catch (error) {
                const { name, message } = error
                errorMsg = message
                console.log('同意/提交 按钮=错误==》', error)
              }
              console.log(errorMsg, 'errorMsg')
              if (
                errorMsg &&
                errorMsg.indexOf(
                  'proxy.$refs.chindRef.callbackSave is not a function'
                ) == -1
              ) {
                btnLoading.value = false
                return false
              }

              proxy.$modal.msgSuccess('操作成功')
              goBack()
              returnOpen.value = false
              btnLoading.value = false
            })
            .catch(error => {
              btnLoading.value = false
            })
          break
        case 'reject':
          proxy.$modal
            .confirm('拒绝审批单流程会终止，是否继续？')
            .then(function () {
              return rejectTask(newParams)
            })
            .then(res => {
              proxy.$modal.msgSuccess('操作成功')
              goBack()
              returnOpen.value = false
              btnLoading.value = false
            })
            .catch(error => {
              btnLoading.value = false
            })
          break
        case 'return':
          // 退回
          btnLoading.value = true
          returnTask(newParams)
            .then(res => {
              proxy.$modal.msgSuccess('操作成功')

              goBack()
              returnOpen.value = false
              btnLoading.value = false
            })
            .catch(error => {
              btnLoading.value = false
            })
          break
        case 'circulation':
          // 传阅
          btnLoading.value = true
          let param = {}
          param.assignee = newParams.copyUserIds
          param.procInsId = newParams.procInsId
          param.variables = newParams.variables
          param.messageTitle = '传阅'
          addCirculation(param)
            .then(res => {
              proxy.$modal.msgSuccess('操作成功')
              returnOpen.value = false
              getProcessDetails(taskHand.value.procInsId, taskHand.value.taskId)
              btnLoading.value = false
            })
            .catch(error => {
              btnLoading.value = false
            })
          break
      }
    }
  })
}

/**流程表单
 * 弹出框 取消
 */
const returnOpenFn = () => {
  appointUserName.value = null
  taskHand.value.comment = undefined
  taskHand.value.nextUserIdsUUID = undefined
  taskHand.value.copyUserIdsUUID = undefined
  taskHand.value.copyUserIds = undefined
  taskHand.value.fileList = []
  fileList.value = []
  replyRecvObj.value.informAllFlag = false
  proxy.resetForm('taskForm')
}
/*************************** 文件上传 start ****/
let fileList = ref([])

/**文件上传 限制条件
 *
 * @param {*} rawFile
 */
function beforeAvatarUpload(rawFile) {
  if (rawFile.size / 1024 / 1024 > 20) {
    proxy.$modal.msgError('单个文件不能超过20MB!')
    return false
  }
}

// 上传合同
async function handleFileChange(params) {
  let formData = new FormData()
  formData.append('file', params.file)
  try {
    const res = await uploadFile(formData)
    if (res.code === 200 && res.data) {
      fileList.value.push(res.data)
    }
  } catch (error) {
    proxy.$modal.msgError(error)
  }
}

// 删除文件
async function delFileName(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      const file = fileList.value[index]
      const res = await delFile(file.fileName)
      if (res.code === 200) {
        fileList.value.splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    proxy.$modal.msgError(error)
  }
}

/************************** 文件上传 end */
/************************** 选择人 模块 start */
const dialogParamUse = ref({})
const selectOptionObj = ref({})

/**
 * 归属人员input获取焦点事件
 */
function userInputFocus(type) {
  dialogParamUse.value = {
    type: type,
    title: '请选择人员',
    dataType: 'person',
    nodeKey: 'uuid',
    multiple:
      type === 'copyUserIds' && signTitle.value === '转审批' ? false : true,
    checkStrictly: false
  }
  if (
    type == 'copyUserIds' &&
    taskHand.value.copyData &&
    JSON.stringify(taskHand.value.copyData) != '[]'
  ) {
    //已抄送人
    dialogParamUse.value.dataType = 'copyUser'
    dialogParamUse.value.data = taskHand.value.copyData
  } else if (type == 'copyUserIds') {
    //抄送人-没固定抄送人的时候
    dialogParamUse.value.apiParams = {
      deptId: 100
    }
  }
  if (type == 'nextUserIds' && toRaw(flowUseData.value).length >= 1) {
    //下一个环节处理人-岗位多人的情况下
    dialogParamUse.value.data = flowUseData.value
  }

  dialogParamUse.value.defaultCheckedKeys =
    type == 'nextUserIds'
      ? taskHand.value.nextUserIdsUUID
      : taskHand.value.copyUserIdsUUID || []
  dialogParamUse.value.isDialog = true
}

/** 弹出框下拉框
 * 项目负责人
 * @param {*} val  selectDialog组件返回的值
 */
const selectDialogData = val => {
  switch (val.type) {
    case 'nextUserIds':
      //下一个环节处理人
      selectOptionObj.value['nextUserIds'] = val.selectData
      taskHand.value.nextUserIdsUUID = val.defaultCheckedKeys
        ? val.defaultCheckedKeys
        : null
      taskHand.value.nextUserIds = val.defaultCheckedKeys
        ? getPricipalId(
            selectOptionObj.value['nextUserIds'],
            val.defaultCheckedKeys
          ).toString()
        : null
      break
    case 'copyUserIds':
      //抄送人
      selectOptionObj.value['copyUserIds'] = val.selectData
      taskHand.value.copyUserIdsUUID = val.defaultCheckedKeys
        ? val.defaultCheckedKeys
        : null
      taskHand.value.copyUserIds = val.defaultCheckedKeys
        ? getPricipalId(
            selectOptionObj.value['copyUserIds'],
            val.defaultCheckedKeys
          )
        : null
      if (signOpen.value && signTitle.value === '加签') {
        //为了加签
        taskHand.value.comment = '审批人：' + val.labelData?.toString()
      }
      break
  }
}
const closeFn = val => {
  dialogParamUse.value.isDialog = false
}
/************************** 选择人 模块 end */
/** 委派任务 */
// function handleDelegate() {
//   proxy.$refs['taskForm'].validate(valid => {
//     if (valid) {
//       userData.value.type = 'delegate'
//       userData.value.title = '委派任务'
//       userData.value.open = true
//       getTreeSelect()
//     }
//   })
// }
// /** 转办任务 */
// function handleTransfer() {
//   proxy.$refs['taskForm'].validate(valid => {
//     if (valid) {
//       userData.value.type = 'transfer'
//       userData.value.title = '转办任务'
//       userData.value.open = true
//       getTreeSelect()
//     }
//   })
// }
watch(
  () => route,
  (newVal, oldVal) => {
    if (location.href.match(/workDetail/)) {
      initData()
      activeName.value = 'businness'
    }
  },
  {
    // deep: true,
    immediate: true
  }
)
/******************************* 项目负责人 模块 end */
</script>
<style>
.workDetail .el-timeline-item__content .el-card__body {
  padding: 15px 20px 15px 20px !important;
}
</style>
<style lang="scss" scoped>
@import '@/assets/styles/variables.module.scss';

:deep(.workDetail-tabs .el-tabs__header) {
  position: fixed;
  width: 100%;
  bottom: 0px;
  z-index: 333;
}

:deep(.el-tabs__content) {
  padding: 0 0 50px;
  border: none;
}

:deep(.el-tabs--border-card) {
  border: none;
}

:deep(.el-tabs--border-card > .el-tabs__header .el-tabs__item.is-active) {
  color: #ffffff;
  background-color: #1890ff;
}

:deep(.el-tabs--border-card > .el-tabs__header .el-tabs__item) {
  color: #1890ff;
}

:deep(.el-tab-pane > .el-card) {
  border: none;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: '';
}

.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
  margin-bottom: 20px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.el-row {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.el-col {
  border-radius: 4px;
}

.button-new-tag {
  margin-left: 10px;
}
</style>
